package com.tencent.wepay.handler.validation;

import java.lang.reflect.Field;
import java.text.MessageFormat;

import org.apache.commons.lang.math.NumberRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tencent.wepay.annotation.Range;
import com.tencent.wepay.handler.ValidationHandler;
import com.tencent.wepay.protocol.domain.Validation;

public class RangeHandler implements ValidationHandler{
	private final static Logger logger=LoggerFactory.getLogger(RangeHandler.class);
	@Override
	public boolean handler(Validation v,Field field) {
		String fieldName=field.getName();
		Range range=(Range) field.getAnnotation(Range.class);
		int min=range.min();
		int max=range.max();
		try {
			Object value=field.get(v);
			if(value==null){
				return true;
			}
			if(max==-1){
				Number number=(Number) value;
				int i;
			    if (number instanceof Double) {
			    	i=new Double(min).compareTo((Double) value);
			    }
			    else if (number instanceof Float) {
			    	i=new Float(min).compareTo((Float) number);
			    }
			    else{
			    	i=new Long(min).compareTo(new Long(value.toString()));
			    }
			    if(i>0){
			    	logger.error("["+fieldName+"]"+MessageFormat.format(range.desc(),min));
			    	return false;
			    }
			    return true;
			}
			NumberRange numberRange=new NumberRange(min, max);
			return numberRange.containsNumber((Number) value);
		}catch (IllegalArgumentException | IllegalAccessException e) {
			logger.error("["+fieldName+"]"+MessageFormat.format(range.desc(),min+"",max+""));
			return false;
		}
	}

	@Override
	public boolean access(Field field) {
		return field.getType().equals(Number.class)||field.getType().getSuperclass().equals(Number.class);
	}
	
}
